package org.example;

import org.apache.zookeeper.*;

import java.io.IOException;

public class ZkClient {

    private static final String ROOT_PATH = "/distribute";

    private final ZooKeeper zooKeeper;

    public ZkClient() throws IOException {
        zooKeeper = new ZooKeeper("127.0.0.1", 30000, watchedEvent -> System.out.println("zookeeper 获取锁成功"));
        try {
            if (zooKeeper.exists(ROOT_PATH, false) == null){
                zooKeeper.create(ROOT_PATH, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        }catch (KeeperException | InterruptedException e){
            e.printStackTrace();
        }
    }

    public ZkDistributedLock getLock(String lockName){
        return new ZkDistributedLock(zooKeeper, lockName);
    }
}
